var defaultReloadIntervals = [
  {str:"3 sec.",         ms:   3000, menuItemId:undefined},
  {str:"5 sec.",         ms:   5000, menuItemId:undefined},
  {str:"7 sec.",         ms:   7000, menuItemId:undefined},
  {str:"10 sec.",        ms:  10000, menuItemId:undefined},
  {str:"15 sec.",        ms:  15000, menuItemId:undefined},
  {str:"20 sec.",        ms:  20000, menuItemId:undefined},
  {str:"30 sec.",        ms:  30000, menuItemId:undefined},
  {str:"1 min.",         ms:  60000, menuItemId:undefined},
  {str:"1 min. 30 sec.", ms:  90000, menuItemId:undefined},
  {str:"2 min.",         ms: 120000, menuItemId:undefined},
  {str:"3 min.",         ms: 180000, menuItemId:undefined},
  {str:"5 min.",         ms: 300000, menuItemId:undefined},
  {str:"10 min.",        ms: 600000, menuItemId:undefined},
  {str:"15 min.",        ms: 900000, menuItemId:undefined},
  {str:"20 min.",        ms:1200000, menuItemId:undefined},
  {str:"30 min.",        ms:1800000, menuItemId:undefined},
  {str:"45 min.",        ms:2700000, menuItemId:undefined},
  {str:"1 hr.",          ms:3600000, menuItemId:undefined}
];

function disableClicked(info, tab) {
   /**
   * Usage: disableClicked(OnClickData info, Tab tab);
   *
   * Description: Determines which job(s) to stop, stops them, and updates
   *   the context menus.
   */

  // Determine whether to stop all jobs or just one
  if (info.menuItemId == radDisableAll) {
      jobs.stop();
  } else stopJob(undefined, tab.id);

  updateContextMenus();
}

function reloadClicked(info, tab) {
   /**
   * Usage: reloadClicked(OnClickData info, Tab tab);
   *
   * Description: Identifies which defaultReloadInterval to run, and then
   *   starts a job for it.
   */
  var defaultReloadInterval;
  for (i in defaultReloadIntervals) {
    if (defaultReloadIntervals[i].menuItemId == info.menuItemId) {
      // Found which defaultReloadInterval correlates to the menu item clicked
      defaultReloadInterval = defaultReloadIntervals[i];
    } else {
      // Uncheck menu items that were not clicked
      chrome.contextMenus.update(
        defaultReloadIntervals[i].menuItemId, {"checked":false}
      );
    }
  }
  // Uncheck disable buttons
  chrome.contextMenus.update(radDisable, {"checked":false});
  chrome.contextMenus.update(radDisableAll, {"checked":false});

  // Start job
  var process = {
    action:"reload", tabIds:[tab.id],
    comment:"Reload selected tab"
  }
  startJob({
    processes:[process], singleTab:true, delay:defaultReloadInterval.ms,
    comment:"Reload selected tab every " + defaultReloadInterval.str
  });
}

function updateContextMenus(tabId) {
  /**
  * Usage: updateContextMenus(integer tabId);
  *
  * Description: Update current context menus for the given tabId.
  * 
  * Fixme: This function needs some cleanup. It's inefficient where efficiency 
  *   counts.
  */
  var matchFound = false;

  // Determine which defaultReloadInterval started this tab's job, if any
  allJobs(function(job, jobNum) {
    if (job.singleTab && job.processes[0].tabIds[0] == tabId &&
        job.processes[0].action == "reload") {
      var checkItem;
      for (i in defaultReloadIntervals) {
        checkItem = false;
        if (defaultReloadIntervals[i].ms == job.delay) {
          // Tab was started by a menu with defaultReloadInterval[i].menuItemId,
          //   or something exactly like it.
          matchFound = checkItem = true;
        }
        chrome.contextMenus.update(
          defaultReloadIntervals[i].menuItemId, {"checked":checkItem}
        );
      }
    }   
  });

  // Indicators of whether a given disable menu item should be checked
  var doCheckDisableAll = false; 
  var doCheckDisable = false;

  // Set menu items accordingly if defaultReloadInterval didn't start this job
  if (!matchFound) {
    for (i in defaultReloadIntervals) {
      chrome.contextMenus.update(
        defaultReloadIntervals[i].menuItemId, {"checked":false}
      );
    }
    
    // If no active jobs exist, all are disabled. Otherwise at least this one is
    doCheckDisableAll = jobs.count() < 1;
    doCheckDisable = !doCheckDisableAll;
  }
  chrome.contextMenus.update(radDisable, {"checked": doCheckDisable});
  chrome.contextMenus.update(radDisableAll, {"checked": doCheckDisableAll});

  // Update sticky menu titles
  var url;
  chrome.tabs.get(tabId, function(tab) {
    url = tab.url;
    chrome.contextMenus.update(radStickUrl, {title: url.substr(0,100)});
  });
}  

/**
* Listeners
*/

// Update context menus on tab change
chrome.tabs.onSelectionChanged.addListener(function(tabId, selectInfo) {
  updateContextMenus(tabId);
});
// Update context menus on window change
chrome.windows.onFocusChanged.addListener(function(windowId) {
  if (windowId != -1) {
    chrome.tabs.getSelected(windowId, function(selectedTab) {
      updateContextMenus(selectedTab.id);
    });
  }
});

// End jobs on tab close (also fired on tabs when a windows is closed)
chrome.tabs.onRemoved.addListener(function(tabId) {
  stopJob(undefined, tabId);
});

/**
* Create Chromatic menu root
*/
var menuRoot = chrome.contextMenus.create({"title": "Chromatic"});
var separator = [];
var sepNum = -1;


/**
* Create menu items for disabling Chromatic
*/
var radDisable = chrome.contextMenus.create({
  "title": "Disable for current tab",
  "type": "radio",
  "checked": false,
  "parentId": menuRoot,
  "onclick":disableClicked
});

var radDisableAll = chrome.contextMenus.create({
  "title": "Disable all",
  "type": "radio",
  "checked": true,
  "parentId": menuRoot,
  "onclick":disableClicked
});

separator[++sepNum] = chrome.contextMenus.create({
  "type": "separator", "parentId": menuRoot 
});


/**
* Create menu items controlling what jobs are sticky to
*/

// Fixme: What I would really like is for each of the sticky menus to propogate
//   with every possible thing the user would like to sticky

var stickToMenu = chrome.contextMenus.create({
  "title": "Stick to",
  "parentId": menuRoot
});

var radStickTab = chrome.contextMenus.create({
  "title": "Tab",
  "type": "radio",
  "checked": true,
  "parentId": stickToMenu,
  "onclick":disableClicked
});

separator[++sepNum] = chrome.contextMenus.create({
  "type": "separator", "parentId": stickToMenu
});

var radStickDomain = chrome.contextMenus.create({
  "title": "Site",
  "type": "radio",
  "checked": false,
  "parentId": stickToMenu,
  "onclick":disableClicked
});

var radStickUrl = chrome.contextMenus.create({
  "title": "Page",
  "type": "radio",
  "checked": false,
  "parentId": stickToMenu,
  "onclick":disableClicked
});

separator[++sepNum] = chrome.contextMenus.create({
  "type": "separator", "parentId": menuRoot 
});

/**
* Generate menu items for reloading tabs
*/
for (i in defaultReloadIntervals) {
  defaultReloadIntervals[i].menuItemId  = chrome.contextMenus.create({
    "title": "Reload page every " + defaultReloadIntervals[i].str,
    "type": "radio",
    "checked": false,
    "parentId": menuRoot,
    "onclick": reloadClicked
  });
}
